package com.mxchip.livestarmobile.mobile.ui.login

import android.app.Application
import android.util.Log
import androidx.lifecycle.*
import com.mxchip.livestarmobile.mobile.Appli
import com.mxchip.livestarmobile.mobile.db.AppDatabase
import com.mxchip.livestarmobile.mobile.db.entity.Account
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class VerifyCodeViewModel(application: Application) : AndroidViewModel(application) {

    private val appDatabase: AppDatabase = (application as Appli).database

    private var countDownJob: Job? = null

    private val _enableResend by lazy {
        MutableLiveData(false)
    }

    val enableResend: LiveData<Boolean>
        get() = _enableResend


    private val _countDownInt by lazy {
        MutableLiveData(60)
    }

    val countDownInt: LiveData<Int>
        get() = _countDownInt


    fun login(number: String, token: String, userId: String) {

        val account = Account(phoneNumber = number, authToken = token, userId = userId)

        GlobalScope.launch {
            appDatabase.accountDao().insertOrUpdate(account)
        }
    }

    fun countDown() {

        countDownJob?.let {
            if(it.isActive) {
                return
            }
        }

        countDownJob = viewModelScope.launch {

            flow {
                (60 downTo 0).forEach {
                    emit(it)
                    delay(1000)
                }
            }.flowOn(Dispatchers.Default)
                    .onStart {
                        // 倒计时开始 ，在这里可以让Button 禁止点击状态
                        _enableResend.value = false
                    }
                    .onCompletion {
                        // 倒计时结束 ，在这里可以让Button 恢复点击状态
                        _enableResend.value = true
                    }
                    .collect {
                        _countDownInt.value = it
                        Log.e("VerifyCodeViewModel", "it $it")
                    }

        }

    }

}
